<template>
  <div @click.stop>
    <div
      class="w-52 h-80 mb-2 border border-solid border-color-lightest rounded-md"
    >
      <!-- 添加图片 -->
      <div class="w-full h-52 flex justify-center items-center bg-slate-300">
        <el-upload
          class="avatar-uploader"
          action="/api/upload"
          name="image"
          @click.prevent
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="imageUrl"
            :src="imageUrl"
            class="w-52 h-52 object-contain"
          />
          <div v-else class="flex items-center flex-col gap-2">
            <i-ep-plus class="text-3xl" />
            <div class="text-sm">上传图片</div>
          </div>
        </el-upload>
      </div>
      <!-- 图片标题和描述 -->
      <div
        class="h-28 text-lg flex flex-col justify-center items-center font-medium"
      >
        <div>{{ picTitle }}</div>
        <div class="text-base text-gray-600">{{ picDesc }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ISetPicUrl } from "@/types/common";
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";

const props = defineProps<{
  picTitle: string;
  picDesc: string;
  index: number;
  value: string;
}>();

const setImageUrl = inject("setImageUrl") as ISetPicUrl;

// - 图片链接
const imageUrl = ref<string>("");

// ? 在上传图片之后监听
// ? 以向服务器发送请求获取图片
watch(
  () => props.value,
  async (newVal) => {
    if (newVal) {
      // - 说明value里面是有链接的，发送服务器请求获取图片
      const response = await fetch(newVal);
      const blob = await response.blob();
      // - 使用 blob 来创建 File 对象
      const file = new File([blob], "image.jpg", { type: blob.type });
      imageUrl.value = URL.createObjectURL(file);
    } else {
      imageUrl.value = "";
    }
    // console.log("imageUrl", imageUrl.value);
  },
  {
    immediate: true,
  },
);

// * 上传成功回调
const handleAvatarSuccess: UploadProps["onSuccess"] = async (
  response,
) => {
  // console.log(response, uploadFile);
  setImageUrl(props.index, response.imageUrl);
};

// * 上传之前回调
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log("beforeAvatarUpload");
  if (rawFile.size > 1024 * 1024 * 2) {
    ElMessage.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};
</script>

<style scoped></style>
